import React, { Component } from "react";
import { Tree } from "antd";
import styles from "./TreeCheckBox.less";

const { TreeNode } = Tree;

const treeData = [
  {
    title: "人员信息",
    key: "人员信息",
    children: [
      {
        title: "人员简要信息",
        key: "人员简要信息"
      },
      {
        title: "首次来沪信息",
        key: "首次来沪信息"
      },
      {
        title: "重点人员登记",
        key: "重点人员登记"
      },
      {
        title: "在逃人员登记",
        key: "在逃人员登记"
      },
      {
        title: "常住人口登记",
        key: "常住人口登记"
      },
      {
        title: "市内最近轨迹记录",
        key: "市内最近轨迹记录"
      }
    ]
  },
  {
    title: "人车关联信息",
    key: "人车关联信息",
    children: [{ title: "关联车辆最近轨迹", key: "关联车辆最近轨迹" }]
  }
];

class TreeCheckBox extends Component {
  state = {
    checkedKeys: []
  };

  static getDerivedStateFromProps(nextProps) {
    if ("value" in nextProps) {
      return {
        checkedKeys: nextProps.value
      };
    }
    return null;
  }

  onCheck = checkedKeys => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(checkedKeys);
    }
  };

  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} key={item.key} />;
    });

  render() {
    const { checkedKeys = [] } = this.state;
    return (
      <div className={styles.root}>
        <Tree
          checkable
          defaultExpandAll={true}
          onCheck={this.onCheck}
          checkedKeys={checkedKeys}
        >
          {this.renderTreeNodes(treeData)}
        </Tree>
      </div>
    );
  }
}

export default TreeCheckBox;
